<template>
  <div class="simple-exercise-creator">
    <div class="page-header">
      <h2>Simple Exercise Creator</h2>
      <div class="header-actions">
        <el-button @click="goBack">
          <el-icon><Back /></el-icon>
          Back
        </el-button>
        <el-button type="primary" @click="generateExercise" :loading="generating" :disabled="!canGenerate">
          <el-icon><Magic /></el-icon>
          Generate Exercise
        </el-button>
      </div>
    </div>

    <div class="creator-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="input-card">
            <template #header>
              <div class="card-header">
                <h3>Input</h3>
              </div>
            </template>
            
            <el-form :model="exerciseInput" label-position="top">
              <el-form-item label="Topic" required>
                <el-input 
                  v-model="exerciseInput.topic" 
                  placeholder="Enter a topic (e.g. JavaScript Arrays, CSS Flexbox, SQL Joins)"
                />
              </el-form-item>
              
              <el-form-item label="Difficulty">
                <el-select v-model="exerciseInput.difficulty" placeholder="Select difficulty level" style="width: 100%">
                  <el-option label="Beginner" value="beginner" />
                  <el-option label="Intermediate" value="intermediate" />
                  <el-option label="Advanced" value="advanced" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="Number of Questions">
                <el-slider 
                  v-model="exerciseInput.questionCount" 
                  :min="3" 
                  :max="20"
                  :step="1"
                  show-stops
                  show-input
                />
              </el-form-item>
              
              <el-form-item label="Additional Instructions (Optional)">
                <el-input 
                  v-model="exerciseInput.instructions" 
                  type="textarea" 
                  :rows="4"
                  placeholder="Add any specific instructions or focus areas for the exercise"
                />
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card class="output-card" :body-style="{ height: '100%' }">
            <template #header>
              <div class="card-header">
                <h3>Generated Exercise</h3>
                <div v-if="generatedExercise.title" class="header-actions">
                  <el-button type="success" size="small" @click="saveExercise" :loading="saving">
                    <el-icon><Check /></el-icon>
                    Save Exercise
                  </el-button>
                  <el-button type="primary" size="small" @click="regenerate" :loading="generating">
                    <el-icon><Refresh /></el-icon>
                    Regenerate
                  </el-button>
                </div>
              </div>
            </template>
            
            <div v-if="generating" class="generating-state">
              <el-skeleton :rows="10" animated />
            </div>
            
            <div v-else-if="!generatedExercise.title" class="empty-state">
              <el-empty description="No exercise generated yet">
                <p>Fill in the form on the left and click "Generate Exercise"</p>
              </el-empty>
            </div>
            
            <div v-else class="exercise-preview">
              <h3 class="exercise-title">{{ generatedExercise.title }}</h3>
              <p class="exercise-description">{{ generatedExercise.description }}</p>
              
              <div class="exercise-meta">
                <el-tag size="small" type="info">{{ generatedExercise.difficulty }}</el-tag>
                <el-tag size="small" type="success">{{ generatedExercise.questions.length }} Questions</el-tag>
              </div>
              
              <div class="questions-preview">
                <h4>Questions Preview:</h4>
                <el-collapse v-model="activePreviewQuestions">
                  <el-collapse-item 
                    v-for="(question, index) in generatedExercise.questions" 
                    :key="index"
                    :name="index"
                  >
                    <template #title>
                      <div class="question-preview-header">
                        <span class="question-number">Question {{ index + 1 }}</span>
                        <span class="question-preview-text">{{ question.text.substring(0, 50) }}{{ question.text.length > 50 ? '...' : '' }}</span>
                      </div>
                    </template>
                    
                    <div class="question-preview-content">
                      <p class="question-text">{{ question.text }}</p>
                      <div class="question-options">
                        <div 
                          v-for="(option, optIndex) in question.options" 
                          :key="optIndex"
                          class="option-item"
                          :class="{ 'correct-option': optIndex === question.correctOption }"
                        >
                          <el-tag 
                            size="small" 
                            :type="optIndex === question.correctOption ? 'success' : 'info'"
                            class="option-marker"
                          >
                            {{ String.fromCharCode(65 + optIndex) }}
                          </el-tag>
                          <span class="option-text">{{ option }}</span>
                        </div>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Back, Magic, Check, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'SimpleExerciseCreator',
  components: {
    Back,
    Magic,
    Check,
    Refresh
  },
  setup() {
    const router = useRouter()
    const generating = ref(false)
    const saving = ref(false)
    const activePreviewQuestions = ref([0])

    const exerciseInput = reactive({
      topic: '',
      difficulty: 'intermediate',
      questionCount: 5,
      instructions: ''
    })

    const generatedExercise = reactive({
      title: '',
      description: '',
      difficulty: '',
      questions: []
    })

    const canGenerate = computed(() => {
      return exerciseInput.topic.trim() !== '' && 
             exerciseInput.difficulty && 
             exerciseInput.questionCount >= 3
    })

    const generateExercise = () => {
      if (!canGenerate.value) {
        ElMessage.warning('Please fill in all required fields')
        return
      }

      generating.value = true

      // In a real application, you would call an API here
      // api.generateExercise(exerciseInput)
      //   .then(response => {
      //     Object.assign(generatedExercise, response.data)
      //   })
      //   .catch(error => {
      //     console.error('Error generating exercise:', error)
      //     ElMessage.error('Failed to generate exercise')
      //   })
      //   .finally(() => {
      //     generating.value = false
      //   })

      // Mock API call with timeout
      setTimeout(() => {
        // Generate a mock exercise based on the input
        const title = `${exerciseInput.topic} - ${exerciseInput.difficulty.charAt(0).toUpperCase() + exerciseInput.difficulty.slice(1)} Level`
        const description = `This exercise set covers ${exerciseInput.topic} at a ${exerciseInput.difficulty} level. ${exerciseInput.instructions ? 'Special focus: ' + exerciseInput.instructions : ''}`
        
        const questions = []
        for (let i = 0; i < exerciseInput.questionCount; i++) {
          const questionNumber = i + 1
          questions.push({
            text: `Sample question ${questionNumber} about ${exerciseInput.topic}?`,
            options: [
              `Option A for question ${questionNumber}`,
              `Option B for question ${questionNumber}`,
              `Option C for question ${questionNumber}`,
              `Option D for question ${questionNumber}`
            ],
            correctOption: Math.floor(Math.random() * 4) // Random correct answer
          })
        }

        Object.assign(generatedExercise, {
          title,
          description,
          difficulty: exerciseInput.difficulty,
          questions
        })

        generating.value = false
      }, 2000)
    }

    const regenerate = () => {
      // Simply call generate again
      generateExercise()
    }

    const saveExercise = () => {
      saving.value = true

      // In a real application, you would call an API here
      // api.saveExercise(generatedExercise)
      //   .then(response => {
      //     ElMessage.success('Exercise saved successfully')
      //     router.push(`/dashboard/exercises/${response.data.id}`)
      //   })
      //   .catch(error => {
      //     console.error('Error saving exercise:', error)
      //     ElMessage.error('Failed to save exercise')
      //   })
      //   .finally(() => {
      //     saving.value = false
      //   })

      // Mock API call with timeout
      setTimeout(() => {
        ElMessage.success('Exercise saved successfully')
        saving.value = false
        router.push('/dashboard/exercises')
      }, 1500)
    }

    const goBack = () => {
      router.push('/dashboard/exercises')
    }

    return {
      exerciseInput,
      generatedExercise,
      generating,
      saving,
      activePreviewQuestions,
      canGenerate,
      generateExercise,
      regenerate,
      saveExercise,
      goBack
    }
  }
}
</script>

<style scoped>
.simple-exercise-creator {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 10px;
}

.creator-container {
  background-color: var(--el-bg-color);
  border-radius: 4px;
}

.input-card, .output-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
}

.generating-state, .empty-state {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.exercise-preview {
  padding: 10px;
  height: 100%;
  overflow-y: auto;
}

.exercise-title {
  margin-top: 0;
  margin-bottom: 10px;
  color: var(--el-color-primary);
}

.exercise-description {
  margin-bottom: 20px;
  color: var(--el-text-color-regular);
}

.exercise-meta {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.questions-preview {
  margin-top: 20px;
}

.questions-preview h4 {
  margin-bottom: 15px;
}

.question-preview-header {
  display: flex;
  align-items: center;
}

.question-number {
  font-weight: bold;
  margin-right: 10px;
  min-width: 100px;
}

.question-preview-text {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.question-preview-content {
  padding: 10px 0;
}

.question-text {
  margin-top: 0;
  margin-bottom: 15px;
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  background-color: var(--el-fill-color-light);
}

.correct-option {
  background-color: var(--el-color-success-light);
}

.option-marker {
  margin-right: 10px;
}

.option-text {
  flex: 1;
}
</style> 